<template>
  <div id="app">
    <van-index-bar>
      <template v-for="(item,index) in brandList">
        <van-index-anchor v-if="item.type === 'title'" :key="item.title" :index="item.title" />
        <van-cell :title="item.title" v-else :key="index" @click="openRightPopup(item.id)" />
      </template>
    </van-index-bar>
    <van-popup v-model="show" position="right" :style="{ width: '80%', height: '100%' }" >
      <template v-for="(item,index) in carList">
        <van-index-anchor v-if="item.type === 'title'" :key="item.id" :index="item.title" />
        <van-card
          :title="item.title" v-else :key="index"
          price="2.00"
          thumb="https://img01.yzcdn.cn/vant/ipad.jpeg"
          @click="$router.push(`/detail/${item.id}`)"
        />
      </template>
    </van-popup>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 响应式
      brandList: [],
      carList: [],
      show: false
    }
  },
  created() {
    this.brandList = []
    this.$api.getBrand().then(res => {
      if (res.success) {
       this.brandList = this.dataToData(res.data)
      }
    })
  },
  methods: {
    dataToData( oldList) {
      let list = []
      const obj = {};
        oldList.forEach(item => {
          if (obj[item.type]) { // obj['A'] = [item]
            obj[item.type].push(item)
          } else {
            obj[item.type] = [item]
          }
        })
        Object.keys(obj).forEach(item => {
          list.push({
            type: "title",
            title: item
          })
          obj[item].forEach(item2 => {
            list.push(item2)
          })
        })
        return list
    },
    openRightPopup(id) {
      this.show = true;
      this.$api.getCarList(id).then(res => {
        if (res.success) {
        this.carList = this.dataToData(res.data)
        }
      })
    }
  }
}
</script>

<style>
* {
  margin: 0;
  padding: 0;
  list-style: none;
}
body,
html,
#app {
  width: 100%;
  height: 100%;
}
</style>